package com.dirtylily.myblog.controller;

import com.dirtylily.myblog.pojo.Comment;
import com.dirtylily.myblog.pojo.User;
import com.dirtylily.myblog.service.BlogService;
import com.dirtylily.myblog.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
public class CommentController {


    @Autowired
    private CommentService commentService;

    @Autowired
    private BlogService blogService;

    @Value("${comment.avatar}")
    private String avatar;

    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId , Model model){
        model.addAttribute("comments",commentService.getAllCommentById(blogId));
        return "blog::commentList";
    }
    @PostMapping("/comments")
    public String post(Comment comment, Model model, HttpSession session){
        Long blogId = comment.getBlog().getId();

        User user = (User) session.getAttribute("user");
        if (user != null) {
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
        } else {
            //设置头像
            comment.setAvatar(avatar);
            comment.setAdminComment(false);

        }

        //设置头像

    //    commentService.saveComment(comment);
        comment.setBlog(blogService.getBlog(blogId));
        commentService.saveComment(comment);
        List<Comment> comments = commentService.getAllCommentById(blogId);
        model.addAttribute("comments", comments);
        return "redirect:/comments/"+ blogId;
    }
}
